using System.Collections.Generic;
using System.Linq;
using UnityEngine;

/// <summary>
/// 实体数据仓库 - 管理所有游戏实体
/// </summary>
public class EntityRepository : IDataRepository<Entity>
{
    private Dictionary<int, Entity> m_Entities = new Dictionary<int, Entity>();
    private int m_NextId = 1;
    
    public Entity GetById(int id)
    {
        m_Entities.TryGetValue(id, out var entity);
        return entity;
    }
    
    public List<Entity> GetAll()
    {
        return m_Entities.Values.ToList();
    }
    
    public List<T> GetByType<T>() where T : Entity
    {
        return m_Entities.Values.OfType<T>().ToList();
    }
    
    public List<Entity> GetByComponent<T>() where T : Component
    {
        return m_Entities.Values.Where(e => e.HasComponent<T>()).ToList();
    }
    
    public void Add(Entity entity)
    {
        if (entity == null) return;
        
        int id = m_NextId++;
        m_Entities[id] = entity;
        
        // 可以添加事件通知
        Logger.Log("EntityRepository", $"Entity {entity.name} added with ID: {id}");
    }
    
    public void Update(Entity entity)
    {
        // 实体更新逻辑
        Logger.Log("EntityRepository", $"Entity {entity.name} updated");
    }
    
    public void Remove(int id)
    {
        if (m_Entities.TryGetValue(id, out var entity))
        {
            m_Entities.Remove(id);
            Logger.Log("EntityRepository", $"Entity {entity.name} removed");
        }
    }
    
    public void Remove(Entity entity)
    {
        var kvp = m_Entities.FirstOrDefault(x => x.Value == entity);
        if (kvp.Key != 0)
        {
            m_Entities.Remove(kvp.Key);
        }
    }
    
    public bool Exists(int id)
    {
        return m_Entities.ContainsKey(id);
    }
    
    public bool Exists(Entity entity)
    {
        return m_Entities.ContainsValue(entity);
    }
    
    public int GetEntityId(Entity entity)
    {
        var kvp = m_Entities.FirstOrDefault(x => x.Value == entity);
        return kvp.Key;
    }
}
